package com.jianguozh.difs.support.service.component.prototypeparam;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.jianguozh.difs.framework.constant.enums.ClientEnum;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 参数管理器
 *
 * @author hanrs
 * @email 40736130@qq.com
 * @since 2022/4/3 9:38 PM
 */
@Component
public class PrototypeParamManager {

    private Root root;

    public PrototypeParamManager() {
        File file = FileUtil.file(this.getClass().getResource("prototype-param.json"));
        String json = FileUtil.readString(file, Charset.defaultCharset());
        this.root = JSONUtil.toBean(json, Root.class);
    }

    public Set<Group> getGroupSet() {
        return root.getGroups();
    }

    public Set<Group> getGroupSetByClient(ClientEnum clientEnum) {
        return getGroupSet().stream().filter(group -> ArrayUtil.indexOf(group.getSetByClientEnum(), clientEnum) > -1).collect(Collectors.toSet());
    }

    public Group getGroupByKey(String key) {
        Set<Group> set = getGroupSet().stream().filter(group -> group.getGroupKey().equalsIgnoreCase(key)).collect(Collectors.toSet());
        return set.iterator().hasNext() ? set.iterator().next() : null;
    }

    public Set<PrototypeParam> getParamSet() {
        Set<PrototypeParam> set = new HashSet<>();
        root.getGroups().forEach(group -> {
            set.addAll(group.getPrototypeParams());
        });
        return set;
    }

    public PrototypeParam getParamByKey(String key) {
        Set<PrototypeParam> set = getParamSet();
        Set<PrototypeParam> prototypeParams = set.stream().filter(prototypeParam -> prototypeParam.getParamKey().equalsIgnoreCase(key)).collect(Collectors.toSet());
        return prototypeParams.iterator().hasNext() ? prototypeParams.iterator().next() : null;
    }

}
